//
//  UIImage+Utils.m
//  WeCaring-养老家属端
//
//  Created by GJS on 2018/9/28.
//  Copyright © 2018年 GJS. All rights reserved.
//

#import "UIImage+Utils.h"

@implementation UIImage (Utils)

/**
 *  @brief 根据self,返回一个按照最大比例切割出来的图片
 *
 *  @param ratio 想要的比例(像素的宽/像素的高)
 *
 *  @return 返回一个按照最大比例切割出来的图片
 */
- (UIImage *)cutImageMaxWithRatio:(CGFloat)ratio {
    CGSize sizeImage = self.size;
    CGFloat fWidthRes;
    CGFloat fHeightRes;
    UIImage *image = [[UIImage alloc] init];
    
    if (sizeImage.width > sizeImage.height) {
        fWidthRes = sizeImage.height / ratio;
        CGFloat fXRes = (sizeImage.width - fWidthRes) / 2;
        CGRect rectRes = CGRectMake(fXRes, 0, fWidthRes, sizeImage.height);
        image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(self.CGImage, rectRes)];
        return image;
    } else if (sizeImage.width < sizeImage.height) {
        fHeightRes = sizeImage.width * ratio;
        CGFloat fYRes = (sizeImage.height - fHeightRes) / 2;
        CGRect rectRes = CGRectMake(0, fYRes, sizeImage.width, fHeightRes);
        image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(self.CGImage, rectRes)];
        return image;
    } else {
        return self;
    }
    return nil;
}

//处理view－>图片
- (UIImage *)captureView:(UIScrollView *)theView{
    CGSize size = theView.contentSize;
    //QLLog(@"captureViewSize:%@",NSStringFromCGSize(size));
    CGFloat fWidth = size.width;
    CGFloat fHeight = size.height;
    
    CGFloat radio = 720.0/fWidth;
    if (radio<1) {
        fHeight = radio*fHeight;
    }
    
    CGSize contextSize = CGSizeMake(720, fHeight);
    
    UIGraphicsBeginImageContext(contextSize);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

//使用该方法不会模糊，根据屏幕密度计算
+ (UIImage *)convertViewToImage:(UIView *)view {
    
    UIImage *imageRet = [[UIImage alloc]init];
    //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度);
    UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageRet;
    
}

- (UIImage*)scaleToSize:(CGSize)size
{
    // 创建一个bitmap的context,并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *imgScaled = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return imgScaled;
}

//ImageType image_type(const char* path)
//{
//    ifstream inFile(path);
//    uchar png_type[9] = {0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,'/0'};
//    uchar file_head[9];
//    for (int i=0;i<8;++i)
//    {
//        inFile>>file_head[i];
//    }
//    file_head[8] = '/0';
//    switch (file_head[0])
//    {
//        case 0xff:
//            if (file_head[1]==0xd8)
//                return jpg;//jpeg
//        case 0x42:
//            if (file_head[1]==0x4D)
//                return bmp;//bmp
//        case 0x89:
//            if (file_head[1]==png_type[1] && file_head[2]==png_type[2] && file_head[3]==png_type[3] && file_head[4]==png_type[4]&&
//                file_head[5]==png_type[5] && file_head[6]==png_type[6] && file_head[7]==png_type[7])
//                return png;//png
//        default:
//            return nothing;
//    }
//}

+ (UIImage *)imageWithName:(NSString *)strImgName {
    NSString *strElemment = @"@2x";
    NSString *strSuffix = @".png";
    if ([strImgName rangeOfString:strElemment].length != 0) {
        if ([strImgName hasSuffix:strSuffix]) {
            strImgName = [strImgName stringByReplacingOccurrencesOfString:strSuffix withString:@""];
        }
        strImgName = [NSString stringWithFormat:@"%@%@", strImgName, strElemment];
    }
    if (![strImgName hasSuffix:strSuffix]) {
        strImgName = [NSString stringWithFormat:@"%@%@", strImgName, strSuffix];
    }
    NSString *strImgPath = [[NSBundle mainBundle] pathForResource:strImgName ofType:nil];
    if (strImgPath == nil) {
        strImgName = [strImgName stringByReplacingOccurrencesOfString:@"@2x" withString:@""];
    }
    strImgPath = [[NSBundle mainBundle] pathForResource:strImgName ofType:nil];
    
    return [UIImage imageWithContentsOfFile:strImgPath];
}

+(UIImage *)colorizeImage:(UIImage *)baseImage withColor:(UIColor *)theColor {
    UIGraphicsBeginImageContext(baseImage.size);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
    
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    
    CGContextSaveGState(ctx);
    CGContextClipToMask(ctx, area, baseImage.CGImage);
    
    [theColor set];
    CGContextFillRect(ctx, area);
    
    CGContextRestoreGState(ctx);
    
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    
    CGContextDrawImage(ctx, area, baseImage.CGImage);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

- (UIImage *)compressToSomeMB:(CGFloat)uploadMB {
    UIImage *thumbImage = [self wcSessionCompress];
    //NSData *data = UIImageJPEGRepresentation(thumbImage, 1.0);
    // 压缩到几兆大小内
    NSData *data = [thumbImage compressToDataMB:uploadMB];
    
    while (uploadMB > 0 && data.length*8 > 1024*1024*uploadMB) {
        UIImage *imgNew = [UIImage imageWithData:data];
        data = UIImageJPEGRepresentation(imgNew, 0.9);
    }
    
    return [UIImage imageWithData:data];
}

// 把上传需要的图片压缩到指定大小
- (NSData *)compressToDataMB:(CGFloat)uploadMB
{
    NSData *imageData = nil;
    
    CGFloat kb = 1 * 1024; // 1KB
    CGFloat mb = 1 * 1024 * kb; // 1MB
    
    uploadMB = uploadMB > 0 ? uploadMB : 1.0; // 1MB
    
    CGFloat itemMB = 0; // 把文件转成MB
    
    CGImageRef cgImageRef = self.CGImage;
    
    size_t bpp = CGImageGetBitsPerPixel(cgImageRef);
    
    //size_t bpc = CGImageGetBitsPerComponent(cgImageRef);
    
    //size_t components_per_pixel = bpp / bpc;
    
    CGFloat lPixelsPerMB = mb / bpp;
    
    CGFloat totalPixel = CGImageGetWidth(cgImageRef) * CGImageGetHeight(cgImageRef);
    
    itemMB = totalPixel / lPixelsPerMB;
    
    if (itemMB <= uploadMB) {
        
        imageData = UIImageJPEGRepresentation(self, 1.0f);
        
    } else {
        
        // 大于1M压到1M
        
        NSUInteger uploadSize = floor(sqrt(uploadMB * lPixelsPerMB));
        
        CGSize imageSize = self.size;
        
        CGSize toImageSize = CGSizeZero;
        
        if (imageSize.width > imageSize.height) {
            
            toImageSize = CGSizeMake(uploadSize, uploadSize * imageSize.height / imageSize.width);
            
        } else if (imageSize.width < imageSize.height) {
            
            toImageSize = CGSizeMake(uploadSize * imageSize.width / imageSize.height, uploadSize);
            
        } else {
            
            //toImageSize = CGSizeMake(sqrt(1048576), sqrt(1048576));
            toImageSize = CGSizeMake(uploadSize, uploadSize);
            
        }
        
        UIImage *toImage = [self scaleToSize:toImageSize];
        
        imageData = UIImageJPEGRepresentation(toImage, 1.f);
        
    }
    
    // 这里注意下:根据自己的需要转成不同类型的NSData字节流...
    
    // 这是不用base64转码返回的string
    
    return imageData;
    
    // 这是用base64转码返回的string,1.0上传的方式
    
    //    Byte *byte = (Byte *)[imageData bytes];
    
    //    return [NSString stringWithFormat:@"jpeg@%@", [GTMBase64 stringByEncodingBytes:byte length:imageData.length]];
    
}

@end
